package com.jake.xpage.demos.applemusic;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jake.xpage.page.IPageAnimator;
import com.jake.xpage.page.XPage;
import com.jake.xpage.page.XPageContainer;
import com.jake.xpage.router.XPageRoute;
import com.jake.xpage.router.XPageRouteMapper;
import com.jake.xpage.router.XPageRouteMapperManager;
import com.jake.xpage.scheme.XPageSchemeInterceptor;
import com.jake.xpage.scheme.XSchemeInterceptManager;

public class AppMusicNavigator {
    private static XPageRouteMapperManager sRouteMapperManager;
    private final static XSchemeInterceptManager SCHEME_INTERCEPT_MANAGER = new XSchemeInterceptManager();
    private static XPageContainer sPageContainer;

    public static void switchContainer(@NonNull XPageContainer container) {
        sPageContainer = container;
        if (sRouteMapperManager == null) {
            sRouteMapperManager = new XPageRouteMapperManager(new XPageRouteMapper.Callback() {
                @Override
                public Context getContext() {
                    return container.getContext();
                }

                @Override
                public void startPage(@NonNull XPage page, @Nullable IPageAnimator animator) {
                    if (sPageContainer != null) {
                        if (animator == null) {
                            animator = sPageContainer.getDefaultAnimator();
                        }
                        sPageContainer.startPage(page, animator);
                    }

                }
            });

            configRouterMapper(sRouteMapperManager);
            configSchemeIntercept(SCHEME_INTERCEPT_MANAGER);
        }

    }

    private static void configSchemeIntercept(@NonNull XSchemeInterceptManager manager) {
        manager.registerInterceptor(new XPageSchemeInterceptor() {
            @Override
            protected boolean handleRoute(@NonNull XPageRoute route) {
                if (sRouteMapperManager != null) {
                    sRouteMapperManager.openRoute(route);
                    return true;
                }
                return false;
            }
        });
    }

    private static void configRouterMapper(@NonNull XPageRouteMapperManager mapperManager) {
        mapperManager.registerRouteMapper(new AppleMusicRouteMapper());
    }


    public static boolean openUrl(String url) {
        return openUrl(url, null);
    }

    public static boolean openUrl(String url, Object extraObj) {
        return SCHEME_INTERCEPT_MANAGER.handleIntercept(url, extraObj);
    }
}
